# coding=gbk
"""
Created on 2016/6/15 0015

@author: Blunce

@about:

"""
import os
import random

import matplotlib.pyplot as plt
import numpy as np

from utils.myUtils import save_as_csv

PATH_ORG = os.getcwd()[:-5] + "data" + os.sep + "org"
PATH_TMP = os.getcwd()[:-5] + "data" + os.sep + "ex07"
ALL_FILE = ["100RR_tms.csv", "100sig_tms.csv", "100ann.csv", "100RR.csv"]


class Ex07:
    def __init__(self):
        pass

    def show_random_ecg(self):
        with open(PATH_TMP + os.sep + "signal_100.csv") as fr:
            lines = fr.readlines()
            # random.shuffle(lines)
            signal = np.array(lines[-2].split(","), dtype=float)
            plt.plot(signal)
            plt.show()

    def split_signal(self):
        beginnings = np.loadtxt(PATH_ORG + os.sep + ALL_FILE[2], dtype=int,
                                delimiter=",")
        signals = np.loadtxt(PATH_ORG + os.sep + ALL_FILE[1], dtype=float,
                             delimiter=",")[:, 0]
        data = []
        for i in range(len(beginnings) - 1):
            data.append(signals[beginnings[i]:beginnings[i + 1]])
        save_as_csv(data, PATH_TMP + os.sep + "signal_100.csv")

    def split_signal_period(self):
        periods = np.loadtxt(PATH_ORG + os.sep + ALL_FILE[3], dtype=int,
                             delimiter=",")
        signals = np.loadtxt(PATH_ORG + os.sep + ALL_FILE[1], dtype=float,
                             delimiter=",")[:, 0]
        data = []
        rear = 0
        for i in range(len(periods) - 1):
            head = np.sum(periods[:i])
            rear = np.sum(periods[:i + 1])
            data.append(signals[head:rear])

        data.append(signals[rear:])
        save_as_csv(data, PATH_TMP + os.sep + "signal_100.csv")

    def __show_random_ecg_in_file(self, filename):
        with open(filename)as fr:
            lines = fr.readlines()
            random.shuffle(lines)
            plt.plot(np.array(lines[0].split(","), dtype=float))
            plt.show()

    def show_9_file_ecg(self):
        from preprocess.preprocess import ANNOTATIONS_DES
        for one in ANNOTATIONS_DES:
            self.__show_random_ecg_in_file(
                os.getcwd()[:-5] + "data" + os.sep +
                "preprocess_data" + os.sep + one + ".csv")


if __name__ == '__main__':
    print "**************start**************\n\n"

    ex07 = Ex07()
    # ex07.split_signal_period()
    # for i in range(10):
    # ex07.show_random_ecg()
    ex07.show_9_file_ecg()

print "\n\n**************end**************"
